package com.magina.controller.login;



import com.magina.api.entity.exception.LoginErrorException;
import com.magina.api.entity.system.TSysMenu;
import com.magina.api.entity.system.TSysUser;
import com.magina.api.service.service.login.LoginService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Bean;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RestController
public class LoginController {

    @Reference
    private LoginService loginService;

    @Bean(name = "loginService")
    public LoginService getIAccountService(){
        return loginService;
    }

    /**
     * 登录逻辑说明
     * @param user
     * @param model
     * @return
     */

    @PostMapping("/login")
    public ModelAndView doLogin(TSysUser user, Model model){

        ModelAndView modelAndView = new ModelAndView();

        modelAndView.setViewName("redirect:/");

        try{
            //具体的登录
            Subject subject = SecurityUtils.getSubject();

            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUserCode(),user.getRPassword());

            //具体逻辑由 MyShiroRealm 实现
            subject.login(usernamePasswordToken);

        }catch (LoginErrorException e){

            model.addAttribute("errorMessage",e.getErrorMsg());

            modelAndView.setViewName("forward:/welcome");
        }

        return modelAndView;
    }

    /**
     *  跳转首页
     *  1, 获取登录者的信息, 获取登录者的菜单信息，放入对象中。
     *  2, 获取菜单树的信息, 存放在对象中
     * @return
     */
    @PostMapping("/main")
    public ModelAndView mainPage( Model model){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("main");
        //1,从shiro中获取登录信息
        TSysUser activityUser = (TSysUser)SecurityUtils.getSubject().getPrincipal();
        //2,从activityUser中获取角色id
        Integer roleId = activityUser.getRoleId();
        List<TSysMenu> menuList = loginService.getMenuTreeList(roleId);
        model.addAttribute("user",activityUser);
        model.addAttribute("menuList",menuList);
        return modelAndView;
    }

}
